package com.leetcode;

public class _34_SearchRange {
    public int[] searchRange(int[] nums, int target) {
        int[] arr = new int[2];
        arr[0] = left_bound(nums,target);
        arr[1] = right_bound(nums,target);
        return arr;
    }

    public  int left_bound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                right = mid - 1;
            }
        }
        if(left >= nums.length) {
            return -1;
        }
        if(nums[left] == target) {
            return left;
        }
        return -1;
    }

    public  int right_bound(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                left = mid + 1;
            }
        }
        if(right < 0) {
            return -1;
        }
        if (nums[right] == target) {
            return right;
        }
        return -1;
    }
}
